//
//  TransferInfoFormViewController.m
//  nonghubao
//
//  Created by Fenrir on 13-5-17.
//  Copyright (c) 2013年 Chongqing Nonghubao Co., Ltd. All rights reserved.
//

#import "TransferInfoFormViewController.h"
#import "Helper.h"
#import "Config.h"
#import <QuartzCore/QuartzCore.h>
#import "JMFBase.h"

//  -业务逻辑细节说明-
//
//  @abstract       本类的业务逻辑较为简单，只是viewDidLoad通过判断option去决定一些view显示的Label的text和UIView是否隐藏。
//                      当option为SECURITY_PASSWORD_MODIFICATION时，表示显示为修改安全密码，则表单中有3个需要填写的数据；
//                      当option为BANK_INFO_MODIFICATION时，表示显示为修改银行信息，则表单中有4个需要填写的数据，此时表单中的textfield会有传递过来的transferInfo设置的默认值；


//  @discussion

//  @notes          


//  -类修改日志-
//  修改人   修改时间   针对版本
//  修改描述


//用于区别显示view的不同状态，SECURITY_PASSWORD_MODIFICATION表明要显示为修改安全密码的表单，BANK_INFO_MODIFICATION表明要显示为修改银行信息的表单
#define SECURITY_PASSWORD_MODIFICATION 3
#define BANK_INFO_MODIFICATION 2


@interface TransferInfoFormViewController ()

@end

@implementation TransferInfoFormViewController
@synthesize transferInfo = _transferInfo;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithOption:(NSInteger)option
{
    self = [super init];
    if (self) {
        
        _option = option;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    if (_option == BANK_INFO_MODIFICATION) {
        [self banksRequest];
    }
    
    UIButton *backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    UIButton *saveButton = [Helper buttonWithStyle:ButtonStyleNavigationSave];
    [saveButton addTarget:self action:@selector(saveButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:saveButton];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
//    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_bg_012@2x" ofType:@"png"]]];
    
    _scrollView = [[CustomScrollView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, _SYS_FRAME_HEIGHT)];
    _scrollView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_bg_012@2x" ofType:@"png"]]];
    _scrollView.customDelegate = self;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    CGSize newSize = CGSizeMake(self.view.frame.size.width, _SYS_FRAME_HEIGHT + 50.0f);
    
    [_scrollView setContentSize:newSize];
    [self.view addSubview:_scrollView];
    
    //当前密码view或者银行卡号View
    UIView* firstView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 300, 40)];
    firstView.backgroundColor = [UIColor whiteColor];
    firstView.layer.cornerRadius = 3;
    firstView.layer.borderWidth = 1;
    firstView.layer.borderColor = [_SYS_COLOR_003 CGColor];
    [_scrollView addSubview:firstView];
    
    //当前密码Label或者银行卡号Label
    _firstLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 75, 20)];
    _firstLabel.font = _SYS_FONT_003;
    
    [firstView addSubview:_firstLabel];
    
    //当前密码输入框或者银行卡号输入框
    _firstTextField = [[UITextField alloc] initWithFrame:CGRectMake(85, 9, 200, 24)];
    _firstTextField.tag = 97;
    _firstTextField.returnKeyType = UIReturnKeyDone;
    _firstTextField.font = _SYS_FONT_003;
    _firstTextField.delegate = self;
    [firstView addSubview:_firstTextField];
    
    
    //新密码view或者开户银行View
    UIView* secondView = [[UIView alloc] initWithFrame:CGRectMake(10, firstView.frame.origin.y + firstView.frame.size.height + 10.0f, 300, 40)];
    secondView.backgroundColor = [UIColor whiteColor];
    secondView.layer.cornerRadius = 3;
    secondView.layer.borderWidth = 1;
    secondView.layer.borderColor = [_SYS_COLOR_003 CGColor];
    [_scrollView addSubview:secondView];
    
    //新密码vLabel或者开户银行Label
    _secondLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 75, 20)];
    _secondLabel.font = _SYS_FONT_003;
    
    [secondView addSubview:_secondLabel];
    
    //新密码v输入框或者开户银行输入框
    _secondTextField = [[UITextField alloc] initWithFrame:CGRectMake(85, 9, 200, 24)];
    _secondTextField.tag = 2;
    _secondTextField.returnKeyType = UIReturnKeyDone;
    _secondTextField.font = _SYS_FONT_003;
    _secondTextField.delegate = self;
    [secondView addSubview:_secondTextField];
    
    //验证密码view或者银行所在地View
    UIView* thirdView = [[UIView alloc] initWithFrame:CGRectMake(10, secondView.frame.origin.y + secondView.frame.size.height + 10.0f, 300, 40)];
    thirdView.backgroundColor = [UIColor whiteColor];
    thirdView.layer.cornerRadius = 3;
    thirdView.layer.borderWidth = 1;
    thirdView.layer.borderColor = [_SYS_COLOR_003 CGColor];
    [_scrollView addSubview:thirdView];
    
    //验证密码Label或者银行所在地Label
    _thirdLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 75, 20)];
    _thirdLabel.font = _SYS_FONT_003;
    
    [thirdView addSubview:_thirdLabel];
    
    //验证密码或者银行所在地输入框
    _thirdTextField = [[UITextField alloc] initWithFrame:CGRectMake(85, 9, 200, 24)];
    _thirdTextField.tag = 3;
    _thirdTextField.returnKeyType = UIReturnKeyDone;
    _thirdTextField.font = _SYS_FONT_003;
    _thirdTextField.delegate = self;
    [thirdView addSubview:_thirdTextField];
    
    //支行View
    UIView* fourthView = [[UIView alloc] initWithFrame:CGRectMake(10, thirdView.frame.origin.y + thirdView.frame.size.height + 10.0f, 300, 40)];
    fourthView.backgroundColor = [UIColor whiteColor];
    fourthView.layer.cornerRadius = 3;
    fourthView.layer.borderWidth = 1;
    fourthView.layer.borderColor = [_SYS_COLOR_003 CGColor];
    [_scrollView addSubview:fourthView];
    
    //支行Label
    _fourthLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 75, 20)];
    _fourthLabel.text = _L(@"title_100");
    _fourthLabel.font = _SYS_FONT_003;
    
    [fourthView addSubview:_fourthLabel];
    
    //支行输入框
    _fourthTextField = [[UITextField alloc] initWithFrame:CGRectMake(85, 9, 200, 24)];
    _fourthTextField.tag = 4;
    _fourthTextField.returnKeyType = UIReturnKeyDone;
    _fourthTextField.font = _SYS_FONT_003;
    _fourthTextField.delegate = self;
    [fourthView addSubview:_fourthTextField];
    
    //身份证View
    UIView* fifthView = [[UIView alloc] initWithFrame:CGRectMake(10, fourthView.frame.origin.y + fourthView.frame.size.height + 10.0f, 300, 40)];
    fifthView.backgroundColor = [UIColor whiteColor];
    fifthView.layer.cornerRadius = 3;
    fifthView.layer.borderWidth = 1;
    fifthView.layer.borderColor = [_SYS_COLOR_003 CGColor];
    [_scrollView addSubview:fifthView];
    
    //身份证Label
    _fifthLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 75, 20)];
    _fifthLabel.text = _L(@"title_57");
    _fifthLabel.font = _SYS_FONT_003;
    
    [fifthView addSubview:_fifthLabel];
    
    //身份证输入框
    _fifthTextField = [[UITextField alloc] initWithFrame:CGRectMake(85, 9, 200, 24)];
    _fifthTextField.tag = 5;
    _fifthTextField.returnKeyType = UIReturnKeyDone;
    _fifthTextField.font = _SYS_FONT_003;
    _fifthTextField.delegate = self;
    [fifthView addSubview:_fifthTextField];
    
    //真实姓名View
    UIView* sixthView = [[UIView alloc] initWithFrame:CGRectMake(10, fifthView.frame.origin.y + fifthView.frame.size.height + 10.0f, 300, 40)];
    sixthView.backgroundColor = [UIColor whiteColor];
    sixthView.layer.cornerRadius = 3;
    sixthView.layer.borderWidth = 1;
    sixthView.layer.borderColor = [_SYS_COLOR_003 CGColor];
    [_scrollView addSubview:sixthView];
    
    //真实姓名Label
    _sixthLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 75, 20)];
    _sixthLabel.text = _L(@"title_58");
    _sixthLabel.font = _SYS_FONT_003;
    
    [sixthView addSubview:_sixthLabel];
    
    //真实姓名输入框
    _sixthTextField = [[UITextField alloc] initWithFrame:CGRectMake(85, 9, 200, 24)];
    _sixthTextField.tag = 6;
    _sixthTextField.returnKeyType = UIReturnKeyDone;
    _sixthTextField.font = _SYS_FONT_003;
    _sixthTextField.delegate = self;
    [sixthView addSubview:_sixthTextField];
    
    //根据用户处理业务的不同，重新定义Label显示方式及内容
    if (_option == SECURITY_PASSWORD_MODIFICATION) {
        
        _firstLabel.text = _L(@"title_61");
        _firstTextField.placeholder = _L(@"holder_25");
        _firstTextField.secureTextEntry = YES;
        
        _secondLabel.text = _L(@"title_62");
        _secondTextField.placeholder = _L(@"holder_23");
        _secondTextField.secureTextEntry = YES;
        
        _thirdLabel.text = _L(@"title_60");
        _thirdTextField.placeholder = _L(@"holder_24");
        _thirdTextField.secureTextEntry = YES;
        
        fourthView.hidden = YES;
        fifthView.hidden = YES;
        sixthView.hidden = YES;
    }
    
    else if (_option == BANK_INFO_MODIFICATION){
        
        _firstLabel.text = _L(@"title_55");
        _secondLabel.text = _L(@"title_56");
        _thirdLabel.text = _L(@"title_74");
        fourthView.hidden = NO;
        fifthView.hidden = NO;
        sixthView.hidden = NO;
        
        if (_transferInfo.count != 0) {
            
            _firstTextField.text = [_transferInfo objectForKey:@"bankAccount"];
            _firstTextField.textColor = [UIColor lightGrayColor];
            _firstTextField.keyboardType = UIKeyboardTypeNumberPad;
            
            _secondTextField.text = [_transferInfo objectForKey:@"bankName"];
            _secondTextField.textColor = [UIColor lightGrayColor];
            
            //如果是直辖市，就指显示一级城市，否则就要显示二级城市
            if ([self isMunicipalityDirectly:[_transferInfo objectForKey:@"provName"]]) {
                _thirdTextField.text = [_transferInfo objectForKey:@"provName"];
            }else{
                _thirdTextField.text = [NSString stringWithFormat:@"%@ %@", [_transferInfo objectForKey:@"provName"], [_transferInfo objectForKey:@"cityName"]];
            }
            
            _currentBankLoc = _thirdTextField.text;
            
            _thirdTextField.textColor = [UIColor lightGrayColor];
            
            _fourthTextField.text = [_transferInfo objectForKey:@"subbranch"];
            _fourthTextField.textColor = [UIColor lightGrayColor];
            
            _fifthTextField.text = [_transferInfo objectForKey:@"idCard"];
            _fifthTextField.textColor = [UIColor lightGrayColor];
            
            _sixthTextField.text = [_transferInfo objectForKey:@"realName"];
            _sixthTextField.textColor = [UIColor lightGrayColor];
            
        }else{
            [Helper showAllTextDialog:_L(@"alert_47") inView:self.view];
        }

    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*!
 @abstract 向服务器请求农户宝支持转账业务的银行集合
 */
- (void)banksRequest
{
    JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ACCOUNT_TRANSFER_BANKNAME_LIST];
    
    NSDictionary* dict = [request synchronous];
    
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        if (_banksDatasource == nil) {
            _banksDatasource = [[NSMutableArray alloc] init];
        }
        
        if (_banksDatasource.count != 0) {
            
            [_banksDatasource removeAllObjects];
        }
        
        [_banksDatasource addObjectsFromArray:(NSArray *)jmf.data];
        
    }
    else {
        
        [Helper easyShowJMFStatus:jmf];
    }
}

//是否是直辖市
- (BOOL)isMunicipalityDirectly:(NSString *)address
{
    if (address == nil) {
        
        return NO;
    }
    
    if ([MUNICIPALITY_DIRECTLY indexOfObject:address] != NSNotFound) {
        
        return YES;
    }
    
    return NO;
}

#pragma mark - 自定义事件

- (void)backButtonEvent:(id)sender
{
    //根据用户处理业务的不同，重新定义Label显示方式及内容
    if (_option == SECURITY_PASSWORD_MODIFICATION) {
        
        if ([_firstTextField.text length] == 0 &&
            [_secondTextField.text length] == 0 &&
            [_thirdTextField.text length] == 0) {
            
            
            [self.navigationController dismissModalViewControllerAnimated:true];
        }
        
        else {
            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_96") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
            [alertView show];
        }
    }
    
    else if (_option == BANK_INFO_MODIFICATION) {
        
        //判断文本域每个值是否等于预设值
        if ([_firstTextField.text isEqualToString:[_transferInfo objectForKey:@"bankAccount"]] &&
            [_secondTextField.text isEqualToString:[_transferInfo objectForKey:@"bankName"]] &&
            [_thirdTextField.text isEqualToString: _currentBankLoc] &&
            [_fourthTextField.text isEqualToString:[_transferInfo objectForKey:@"subbranch"]] &&
            [_fifthTextField.text isEqualToString:[_transferInfo objectForKey:@"idCard"]] &&
            [_sixthTextField.text isEqualToString:[_transferInfo objectForKey:@"realName"]])
        {
            
            [self.navigationController dismissModalViewControllerAnimated:true]; 
        }
        
        else {
            
            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_95") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
            
            [alertView show];
        }
    }
}


- (void)saveButtonEvent:(id)sender
{
    JSONRequest* request = nil;
    
    if (_option == SECURITY_PASSWORD_MODIFICATION) {

        request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ACCOUNT_TRANSFER_SECURITYPWD];
        
        [request setValue:_firstTextField.text  forParameter:@"oldSecurityPwd"];         //当前密码
        [request setValue:_secondTextField.text forParameter:@"securityPwd"];            //新密码
        [request setValue:_thirdTextField.text  forParameter:@"confirmPwd"];              //验证密码
    }
    
    else if (_option == BANK_INFO_MODIFICATION){
        
        request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ACCOUNT_TRANSFER_CNANGE_BANK];
        
        [request setValue:_firstTextField.text forParameter:@"bankAccount"];         //银行卡号
        
        [request setValue:_secondTextField.text forParameter:@"bankName"];           //开户行名称
        
        [request setValue:_provName forParameter:@"provName"];                  //开户行所在地一级城市名
        [request setValue:_cityName forParameter:@"cityName"];                  //开户行所在地二级城市名
        [request setValue:_fourthTextField.text forParameter:@"subbranch"];           //支行
        [request setValue:_fifthTextField.text forParameter:@"idCard"];           //身份证号码
        
        [request setValue:_sixthTextField.text forParameter:@"realName"];           //真实姓名
        
    }
    
    [request setValue:[_transferInfo objectForKey:@"id"] forParameter:@"transferAccountId"];
    request.hudOn = true;
    request.delegate = self;
    request.hudTitle = _L(@"title_loading_13");
    
    [request asynchronous];
}

#pragma mark - UITextField Delegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    UIView *superView = [textField superview];
    
    float offset = superView.frame.origin.y + superView.frame.size.height - (self.view.frame.size.height - 246);
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    if(offset > 0)
    {        
        _scrollView.contentOffset = CGPointMake(0.0f, offset);
    }
    
    [UIView commitAnimations];
    
    if (_option == BANK_INFO_MODIFICATION)
    {
        //点击后删除之前的PickerView
        for (UIView *view in self.view.subviews) {
            if ([view isKindOfClass:[UICustomPickerView class]]) {
                [view removeFromSuperview];
            }
        }
        
        //开户银行
        if (textField.tag == 2) {
            
            [_firstTextField resignFirstResponder];
            [_thirdTextField resignFirstResponder];
            [_fourthTextField resignFirstResponder];
            [_fifthTextField resignFirstResponder];
            [_sixthTextField resignFirstResponder];
            
            _customPickerView = [[UICustomPickerView alloc] initWithFrame:CGRectMake(0,_SYS_FRAME_HEIGHT - 260-44, 320, 260)];
            _customPickerView.delegate = self;
            _customPickerView.dataSource = self;
            
            [self.view addSubview:_customPickerView];
            
            [_customPickerView pickerShow:UICustomPickerViewNormalType];
            
            NSInteger selectedRow = [_banksDatasource indexOfObject:textField.text];
            
            if (selectedRow != NSNotFound) {
                
                [_customPickerView selectRow:selectedRow inComponent:0 animated:NO];
            }
            
            return NO;
        }
        
        if (textField.tag == 3) {
            
            [_firstTextField resignFirstResponder];
            [_secondTextField resignFirstResponder];
            [_fourthTextField resignFirstResponder];
            [_fifthTextField resignFirstResponder];
            [_sixthTextField resignFirstResponder];
            
            _customPickerView = [[UICustomPickerView alloc] initWithFrame:CGRectMake(0,_SYS_FRAME_HEIGHT - 260-44, 320, 260)];
            _customPickerView.delegate = self;
            _customPickerView.location = textField.text;
            _customPickerView.hzAreaPickerStyle = HZAreaPickerWithStateAndCity;
            _customPickerView.areaPickerOption = HZAreaPickerInitAddtionnalOption;
            [self.view addSubview:_customPickerView];
            
            [_customPickerView pickerShow:UICustomPickerViewAreaType];
            
            return NO;
        }
    }
        
    return YES;
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{    
    [textField resignFirstResponder];
    return YES;
}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_firstTextField resignFirstResponder];
    [_secondTextField resignFirstResponder];
    [_thirdTextField resignFirstResponder];
    [_fourthTextField resignFirstResponder];
    [_sixthTextField resignFirstResponder];
}


#pragma mark - JSONRequestDelegate

- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        [self.navigationController dismissModalViewControllerAnimated:YES];
        
        if (_option == SECURITY_PASSWORD_MODIFICATION) {
            
            [Helper showAllTextDialog:_L(@"alert_49") inView:self.view];
        }
        
        else if (_option == BANK_INFO_MODIFICATION){
            
            [Helper showAllTextDialog:_L(@"alert_48") inView:self.view];
        }
        
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

//
- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}

#pragma mark - UICustomPickerView DataSource

- (NSInteger)numberOfComponentsInUICustomPickerView:(UICustomPickerView *)customPickerView
{
    return 1;
}
- (NSInteger)customPickerView:(UICustomPickerView *)customPickerView
      numberOfRowsInComponent:(NSInteger)component
{
    return _banksDatasource.count;
}

#pragma mark - UICustomPickerView Delegate

- (NSString *)customPickerView:(UICustomPickerView *)customPickerView titleForRow:(NSInteger)row
                  forComponent:(NSInteger)component
{
    return _banksDatasource[row];
}

- (void)customPickerView:(UICustomPickerView *)customPickerView didSelectRow:(NSInteger)row
             inComponent:(NSInteger)component
{
    _secondTextField.text = _banksDatasource[row];
}

- (void)customPickerView:(UICustomPickerView *)customPickerView areaStringReceived:(NSString *)area
{

    NSArray *areaArray = [area componentsSeparatedByString:@" "];
    
    //如果是直辖市，那么一级城市和二级城市要一样，否则不一样。
//    if ([self isMunicipalityDirectly:areaArray[0]]) {
//        
//        _provName = areaArray[0];
//        _cityName = areaArray[0];
//        
//        _thirdTextField.text = _provName;
//    }
//    else {
    
        _provName = areaArray[0];
        _cityName = @"";
        if (areaArray.count > 1) {
            
            _cityName = areaArray[1];
        }
    
        _thirdTextField.text = area;
//    }
}


#pragma mark - UIAlertView Delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        
        [self.navigationController dismissModalViewControllerAnimated:YES];
    }
}
@end
